package com.hmdp.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
@Slf4j
public class RedisIdWorker {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    private static final long BEGIN_TIMESTAMP = 1715440770; // 2024/05/11
    private static final int COUNT_BITS = 32;
    public long nextId(String keyPrefix) {
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        // 当前时间戳减去开始时间戳 这样能让时间戳从0开始计算 能用更久
        long diffTimesTamp = nowSecond - BEGIN_TIMESTAMP;
        // 获取当前格式化时间 精确到某一天 2024:05:11
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 对当天的value进行自增长
        long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        // 对时间戳左移32位，右边就能空出32位，通过 | increment 将右边32为补齐
        // 这里的时间戳会精确到秒，所以一秒内能设置32bit的id数
        return diffTimesTamp << COUNT_BITS | increment;
    }

}
